<?php

require_once "../common/login.php";

$string_war = "//div[@class='middle']";
$string_battle = "//div[@class='listing']/a";
$string_rbattle = "//div[@class='listing resistance']/a";

$format = "Y-m-d?H:i:sP";

$username = "";
$userpass = "";


function ParseBattlePage($link)
{
	global $pageCURL;
	global $string_battle, $string_rbattle;
	global $battle_array;
	
	$filename = "http://www.erepublik.com$link";
	$file = $pageCURL->getPage($filename);
	
	$doc = new DOMDocument();
	$doc->loadHTML($file);
	$xpath = new DOMXpath($doc);
	
	$result1 = $xpath->query($string_battle);
	$result2 = $xpath->query($string_rbattle);
	
	if ($result1->length > 0) {
		$battleLink = $result1->item(0)->getAttribute('href');
		$id = substr(strrchr($battleLink, '/'), 1);
		echo "find active battle $id\n";
		$battle_array[] = $id;
	} else if ($result2->length > 0) {
		$battleLink = $result2->item(0)->getAttribute('href');
		// http://www.erepublik.com/en/military/battlefield-choose-side/5694/30
		$tmp = substr($battleLink, 0, strrpos($battleLink, '/'));
		$id = substr(strrchr($tmp, '/'), 1);
		echo "find active battle $id\n";
		$battle_array[] = $id;		
	}	else {
		echo "no active battle in $link\n";
	}

}


function ParseWarPage($page)
{
	global $pageCURL;
	global $string_war;
	
	$filename = "http://www.erepublik.com/en/wars/$page";
	$file = $pageCURL->getPage($filename);
	
	$doc = new DOMDocument();
	$doc->loadHTML($file);
	$xpath = new DOMXpath($doc);
	
	$wars = $xpath->query($string_war);
	
	foreach($wars as $war) {
		$link = $war->childNodes->item(1)->getAttribute('href');
		$text = $war->childNodes->item(2)->textContent;
		if ( strpos($text, "no") === false ) {
			ParseBattlePage($link);
		} else {
			echo "no active battle in $link\n";
		}
	}
	
	$returncode = TRUE;
	if ( strrpos($file, "Go to next page") === FALSE ) {
		echo "\nAll pages parsed\n";
		$returncode = FALSE;
	}
	
	return $returncode;
}


function ParseOne($id)
{
	global $apiCURL;
	global $format;

	$file = $apiCURL->get("http://api.erepublik.com/v2/feeds/battles/$id");
	$xml = new SimpleXMLElement($file);
	$result = '';
	
	try {
		if ($xml->getName() != "battle") {
			throw new Exception("Error occured when getting battle $id info.");
		}
		
		if ( $xml->progress->{'finished-at'}['nil'] != 'true' ) {
			throw new Exception("Battle $id finished.");
		}
		
		$rid = $xml->region->id;
		$file = $apiCURL->get("http://api.erepublik.com/v2/feeds/regions/$rid");
		
		$xml_r = new SimpleXMLElement($file);
		if ($xml_r->getName() != "region") {
			throw new Exception("Error occured when getting region $rid info.");
		}
		
		if ($xml_r->buildings->hospitals->hospital->count() == 0) {
			throw new Exception("There is no hospital in Battle $id ");
		}
		
		echo "There are hospitals in Battle $id\n";
		
		$zone = new DateTimeZone("Asia/Shanghai");
		$date = DateTime::createFromFormat($format, $xml->progress->{'started-at'}, $zone);
		$date->setTimezone($zone);
		
		$result .= "Region: " . $xml->region->name . " (http://www.erepublik.com/en/military/battlefield/$id)\r\n";
		$result .= "Attacker: " . ($xml->{'is-resistance'} == 'true'? "Resistance of " : "") . $xml->attacker->name . "\r\n";
		$result .= "Defender: " . $xml->defender->name . "\r\n";
		$result .= "Start at: " . $date->format('Y-m-d H:i:s') . "\r\n";
		$result .= "Hospital: ";
		
		foreach ($xml_r->buildings->hospitals->hospital as $hospital) {
			$result .= $hospital->{'zone-id'} . '(' . $hospital->{'wellness-budget'} .
				'/' . $hospital->{'max-heal-per-citizen'} . '); ';
		}
		
		$result .= "\r\n\r\n";
	
	} catch (Exception $e) {
		echo 'Caught exception: ',  $e->getMessage(), "\n";
	}
	
	return $result;
	
}


// main 

$pageCURL = new loginObj();

if ( $pageCURL->login($username, $userpass) == TRUE ) {
	echo "Login succeed.\n";
} else {
	die("Login failed.\n");
}

libxml_use_internal_errors(true);

$battle_array = array();
$i = 0;

do {
	++$i;
	echo "\nParsing page $i ...\n";
	$result = ParseWarPage($i);
} while ($result);


$content = '';
$apiCURL = new cUrl();

echo "\nParsing regions ...\n";

foreach($battle_array as $battle) {
	$content .= ParseOne($battle);
}

$file = fopen('hospital.txt', 'w');
fwrite($file, $content);
fclose($file);

?>
